﻿
namespace ComTools.Map
{
    using Extensions;
    using Helpers;
    using System;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;
    using System.Text;
    using ThoughtWorks.QRCode.Codec;
    using ThoughtWorks.QRCode.Codec.Data;

    /// <summary>
    /// 二维码的帮助类，可生成二维码和解析二维码
    /// </summary>
    public class QRCodeHelper
    {

        /// <summary>
        /// 创建二维码
        /// </summary>
        /// <param name="stringContent">二维码的内容</param>
        /// <returns>创建的图片内容字节数组</returns>
        /// <exception cref="Exception"></exception>
        public static byte[] GenerateQRCodePic(string stringContent)
        {
            try
            {
                byte[] retBytes = null;

                QRCodeEncoder endocder = new QRCodeEncoder();
                //二维码背景颜色
                endocder.QRCodeBackgroundColor = Color.White;
                //二维码编码方式
                endocder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
                //每个小方格的宽度
                endocder.QRCodeScale = 10;
                //二维码版本号
                endocder.QRCodeVersion = 5;
                //纠错等级
                endocder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
                //将内容做成二维码
                using (MemoryStream stream = new MemoryStream())
                {
                    using (Bitmap bitmap = endocder.Encode(stringContent, Encoding.UTF8))
                    {
                        bitmap.Save(stream, ImageFormat.Png);
                        retBytes = new byte[stream.Length];
                        stream.Seek(0, SeekOrigin.Begin);
                        stream.Read(retBytes, 0, Convert.ToInt32(stream.Length));
                    }
                }
                return retBytes;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 创建二维码
        /// </summary>
        /// <param name="rootPath">图片保存的根目录</param>
        /// <param name="stringContent">二维码的内容</param>
        /// <returns>创建好的文件的路径</returns>
        /// <exception cref="DirectoryNotFoundException"></exception>
        /// <exception cref="Exception"></exception>
        public static string GenerateQRCodePic(string rootPath, string stringContent)
        {
            try
            {
                if (!Directory.Exists(rootPath)) throw new DirectoryNotFoundException("未找到文件存放位置根目录：{0}".FormatString(rootPath));

                var retFilePath = Path.Combine(rootPath, "{0}.png".FormatString(GuidHelper.GetSecuentialGuid()));

                var imgBytes = GenerateQRCodePic(stringContent);

                using (MemoryStream stream = new MemoryStream(imgBytes))
                {
                    using (Bitmap map = new Bitmap(stream))
                    {
                        map.Save(retFilePath);
                    }
                }
                return retFilePath;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 二维码解码字符串内容
        /// </summary>
        /// <param name="imgBytesData">二维码byte数据</param>
        /// <returns>解码的内容</returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="Exception"></exception>
        public static string DeCodeQRCode(byte[] imgBytesData)
        {
            if (null == imgBytesData || imgBytesData.Length == 0) throw new ArgumentNullException("imgBytesData");
            try
            {
                var retStringContent = string.Empty;

                using (MemoryStream stream = new MemoryStream(imgBytesData))
                {
                    using (Bitmap map = new Bitmap(stream))
                    {
                        QRCodeImage image = new QRCodeBitmapImage(map);
                        QRCodeDecoder decoder = new QRCodeDecoder();
                        retStringContent = decoder.decode(image, Encoding.UTF8);
                    }
                }
                return retStringContent;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 二维码解码字符串内容
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>解码的内容</returns>
        /// <exception cref="FileNotFoundException"></exception>
        /// <exception cref="Exception"></exception>
        public static string DeCodeQRCode(string filePath)
        {
            if (!File.Exists(filePath)) throw new FileNotFoundException("未找到需要解码的二维码文件：{0}".FormatString(filePath));

            try
            {
                using (FileStream stream = new FileStream(filePath, FileMode.Open))
                {
                    byte[] imgBytesData = new byte[stream.Length];
                    stream.Read(imgBytesData, 0, imgBytesData.Length);
                    return DeCodeQRCode(imgBytesData);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
